using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using net.notdot.Attercop;
using System.Net;
using System.Security.Cryptography;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace net.notdot.Attercop.Client
{
    public partial class MainWindow : Form
    {
        UserSettings user = new UserSettings();
        NetworkSettings network = new NetworkSettings();

        public static MainWindow Instance = null;

        public MainWindow()
        {
            InitializeComponent();
            Instance = this;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingsWindow settings = new SettingsWindow(user, network);
            settings.MdiParent = this;
            settings.Show();
        }

        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ClientInstance c = new ClientInstance(network, user, new FileHandler());
            connectToolStripMenuItem.Visible = false;
            disconnectToolStripMenuItem.Visible = true;
            ServerWindow serverWin = new ServerWindow(c);
            serverWin.MdiParent = this;
            serverWin.Show();
        }

        private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //TODO: Add disconnect method
            connectToolStripMenuItem.Visible = true;
            disconnectToolStripMenuItem.Visible = false;
        }

        private void MainWindow_Load(object sender, EventArgs e)
        {
            Program.HashTasks.OnTaskCompleted += new EventHandler<TaskCompletedEventArgs>(hashtasks_TaskCompleted);
            Program.HashTasks.OnCompleted += new EventHandler(hashtasks_OnCompleted);
            Program.HashTasks.OnStarted += new EventHandler(hashtasks_OnStarted);

            user = UserSettings.Load("usersettings.dat");

            if(File.Exists("networksettings.dat")) {
                BinaryFormatter formatter = new BinaryFormatter();
                FileStream s = new FileStream("networksettings.dat", FileMode.Open, FileAccess.Read);
                network = (NetworkSettings) formatter.Deserialize(s);
                s.Close();
            }
        }

        private void hashtasks_TaskCompleted(object sender, TaskCompletedEventArgs args)
        {
            this.Invoke(new VoidDelegate(delegate() {
                lblStatus.Text = string.Format("[{0:t}] Finished hashing \"{1}\"", DateTime.Now, ((TreeBuilder.HashTask)args.Task).info.FullName);
            }));
        }

        private void hashtasks_OnCompleted(object sender, EventArgs args)
        {
            this.Invoke(new VoidDelegate(delegate()
            {
                lblStatus.Text = string.Format("[{0:t}] Finished hashing all files.", DateTime.Now);

                //Disable the progress timer
                progressTimer.Enabled = false;
                
                pbMain.Value = 0;
            }));

            //Save the hash cache
            HashCache.Save();            
        }

        private void hashtasks_OnStarted(object sender, EventArgs args)
        {
            this.Invoke(new VoidDelegate(delegate()
            {
                progressTimer.Enabled = true;
            }));
        }

        private void progressTimer_Tick(object sender, EventArgs e)
        {
            this.Invoke(new VoidDelegate(delegate()
            {
                pbMain.Value = (int) (Program.HashTasks.TaskComplete / Program.HashTasks.TaskSize * 100);
            }));
        }

        private void MainWindow_FormClosed(object sender, FormClosedEventArgs e)
        {
            Program.HashTasks.Stop();
            HashCache.Save();

            user.Save();
            
            FileStream s = new FileStream("networksettings.dat", FileMode.OpenOrCreate, FileAccess.Write);
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(s, network);
            s.Close();
        }

        private void tsbSearch_Click(object sender, EventArgs e)
        {
            SearchWindow win = new SearchWindow(((ServerWindow)ActiveMdiChild).ClientInstance);
            win.MdiParent = this;
            win.Show();
        }

        private void MainWindow_MdiChildActivate(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild is ServerWindow)
            {
                tsbSearch.Enabled = true;
            }
            else
            {
                tsbSearch.Enabled = false;
            }
        }

        public void AddFileIcon(string extension)
        {
            if (imlSmallFileIcons.Images.ContainsKey(extension))
                return;
            
            imlSmallFileIcons.Images.Add(extension, IconExtractor.GetAssociatedIcon(extension, false));
        }

        private void tsbViewList_Click(object sender, EventArgs e)
        {
            BrowseWindow bw = new BrowseWindow(user.SharedDirectories.Values);
            bw.MdiParent = this;
            bw.Show();
        }
    }
}